From 3f384749fe51a2763e7e99351f36ce70954afb7a Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Mon, 2 Sep 2024 14:40:34 +0700
Subject: <iman> temp save

---
 src/pages/shop/promo/[slug].jsx | 550 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 550 insertions(+)
 create mode 100644 src/pages/shop/promo/[slug].jsx

(limited to 'src/pages/shop/promo/[slug].jsx')

diff --git a/src/pages/shop/promo/[slug].jsx b/src/pages/shop/promo/[slug].jsx
new file mode 100644
index 00000000..544286f9
--- /dev/null
+++ b/src/pages/shop/promo/[slug].jsx
@@ -0,0 +1,550 @@
+import dynamic from 'next/dynamic'
+import NextImage from 'next/image';
+import { useEffect, useState } from 'react'
+import { useRouter } from 'next/router'
+import Seo from '../../../core/components/Seo.jsx'
+import Promocrumb from '../../../lib/promo/components/Promocrumb.jsx'
+import { fetchPromoItemsSolr, fetchVariantSolr } from '../../../api/promoApi.js'
+import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
+import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card.tsx'
+import { IPromotion } from '../../../../src-migrate/types/promotion.ts'
+import React from 'react'
+import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
+import DesktopView from '../../../core/components/views/DesktopView.jsx';
+import MobileView from '../../../core/components/views/MobileView.jsx';
+import 'swiper/swiper-bundle.css';
+import useDevice from '../../../core/hooks/useDevice.js'
+import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktopPromotion.jsx';
+import ProductFilter from '../../../lib/product/components/ProductFilter.jsx';
+import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
+import { formatCurrency } from '../../../core/utils/formatValue.js';
+import Pagination from '../../../core/components/elements/Pagination/Pagination.js';
+import SideBanner from '../../../../src-migrate/modules/side-banner/index.tsx';
+import whatsappUrl from '../../../core/utils/whatsappUrl.js';
+import { cons, toQuery } from 'lodash-contrib';
+import _ from 'lodash';
+import useActive from '../../../core/hooks/useActive.js';
+import useProductSearch from '../../../lib/product/hooks/useProductSearch.js';
+
+const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout.jsx'))
+
+export default function PromoDetail() {
+  const router = useRouter()
+  const { slug = '', brand ='', category='', priceFrom = '', priceTo = '', page = '1' } = router.query
+  const [promoItems, setPromoItems] = useState([])
+  const [promoData, setPromoData] = useState(null)
+  const [currentPage, setCurrentPage] = useState(parseInt(10) || 1);
+  const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
+  const [loading, setLoading] = useState(true);
+  const { isMobile, isDesktop } = useDevice()
+  const [brands, setBrands] = useState([]);
+  const [categories, setCategories] = useState([]);
+  const [brandValues, setBrandValues] = useState([]);
+  const [categoryValues, setCategoryValues] = useState([]);
+  const [orderBy, setOrderBy] = useState(router.query?.orderBy);
+  const popup = useActive();
+  const prefixUrl = `/shop/promo/${slug}`
+  const [queryFinal, setQueryFinal] = useState({});
+  const [limit, setLimit] = useState<number>(30);
+  const [q, setQ] = useState('*');
+  const [finalQuery, setFinalQuery] = useState({fq: `type_value_s:${slug}`});
+  const [products, setProducts] = useState(null);
+  useEffect(() => {
+    setQueryFinal({ ...finalQuery, q, limit, orderBy });
+}, [router.query, prefixUrl, slug, brand, category, priceFrom, priceTo, currentPage]);
+  useEffect(() => {
+      setQueryFinal({ ...finalQuery, q, limit, orderBy });
+  }, [router.query, prefixUrl, slug, brand, category, priceFrom, priceTo, currentPage]);
+
+  const { productSearch } = useProductSearch({
+    query: queryFinal,
+    operation: 'OR',
+  });
+
+  console.log("productSearch",productSearch)
+  console.log("queryFinal",queryFinal)
+
+  const pageCount = Math.ceil(productSearch.data?.response.numFound / limit);
+  const productStart = productSearch.data?.responseHeader.params.start;
+  const productRows = limit;
+  const productFound = productSearch.data?.response.numFound;
+
+  useEffect(() => {
+    setProducts(productSearch.data?.response?.products);
+  }, [productSearch]);
+
+  console.log("products",products)
+
+
+
+
+
+
+
+  useEffect(() => {
+    if (router.query.brand) {
+      let brandsArray= [];
+      if (Array.isArray(router.query.brand)) {
+        brandsArray = router.query.brand;
+      } else if (typeof router.query.brand === 'string') {
+        brandsArray = router.query.brand.split(',').map((brand) => brand.trim());
+      }
+      setBrandValues(brandsArray);
+    } else {
+      setBrandValues([]);
+    }
+
+    if (router.query.category) {
+      let categoriesArray= [];
+
+      if (Array.isArray(router.query.category)) {
+        categoriesArray = router.query.category;
+      } else if (typeof router.query.category === 'string') {
+        categoriesArray = router.query.category.split(',').map((category) => category.trim());
+      }
+      setCategoryValues(categoriesArray);
+    } else {
+      setCategoryValues([]);
+    }
+  }, [router.query.brand, router.query.category]);
+
+  useEffect(() => {
+    const loadPromo = async () => {
+      setLoading(true);
+      const brandsData = [];
+      const categoriesData= [];
+      
+      const pageNumber = Array.isArray(page) ? parseInt(page[0], 10) : parseInt(page, 10);
+      setCurrentPage(pageNumber)
+      
+      try {
+        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`,0,10);
+        setPromoItems(items);
+        
+        if (items.length === 0) {
+          setPromoData([])
+          setLoading(false);
+          return;
+          }
+          
+          const brandArray = Array.isArray(brand) ? brand : brand.split(',');
+          const categoryArray = Array.isArray(category) ? category : category.split(',');
+          
+          const promoDataPromises = items.map(async (item) => {
+            
+            try { 
+              let brandQuery = '';
+              if (brand) {
+                brandQuery = brandArray.map(b => `manufacture_name_s:${b}`).join(' OR ');
+                brandQuery = `(${brandQuery})`;
+              }
+  
+              let categoryQuery = '';
+              if (category) {
+                categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
+                categoryQuery = `(${categoryQuery})`;
+              }
+  
+              let priceQuery = '';
+              if (priceFrom && priceTo) {
+                priceQuery = `price_f:[${priceFrom} TO ${priceTo}]`;
+              } else if (priceFrom) {
+                priceQuery = `price_f:[${priceFrom} TO *]`;
+              } else if (priceTo) {
+                priceQuery = `price_f:[* TO ${priceTo}]`;
+              }
+  
+              let combinedQuery = '';
+              let combinedQueryPrice = `${priceQuery}`;
+              if (brand && category && priceFrom || priceTo) {
+                combinedQuery = `${brandQuery} AND ${categoryQuery} `;
+              } else if (brand && category) {
+                combinedQuery = `${brandQuery} AND ${categoryQuery}`;
+              } else if (brand && priceFrom || priceTo) {
+                combinedQuery = `${brandQuery}`;
+              } else if (category && priceFrom || priceTo) {
+                combinedQuery = `${categoryQuery}`;
+              } else if (brand) {
+                combinedQuery = brandQuery;
+              } else if (category) {
+                combinedQuery = categoryQuery;
+              }
+  
+              if (combinedQuery && priceFrom || priceTo) {
+                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
+                const product = response.response.docs[0];
+                const product_id = product.id;
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`,0,100);  
+                return response2;
+              }else if(combinedQuery){
+                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
+                const product = response.response.docs[0];
+                const product_id = product.id;
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `,0,100); 
+                return response2;
+              } else {
+                const response = await fetchPromoItemsSolr(`id:${item.id}`,0,100);
+                return response;
+              }
+            } catch (fetchError) {
+              return [];
+            }
+          });
+
+        const promoDataArray = await Promise.all(promoDataPromises);
+        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
+        setPromoData(mergedPromoData);
+
+        const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
+          if (promoData) {
+            const dataBrandCategory = promoData.map(async (item) => {
+              let response;
+              if(category){
+                const categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
+                response = await fetchVariantSolr(`id:${item.products[0].product_id} AND (${categoryQuery})`);
+              }else{
+                response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
+              }
+              
+
+              if (response.response?.docs?.length > 0) {
+                const product = response.response.docs[0];
+                const manufactureNameS = product.manufacture_name;
+                if (Array.isArray(manufactureNameS)) {
+                  for (let i = 0; i < manufactureNameS.length; i += 2) {
+                    const brand = manufactureNameS[i];
+                    const qty = 1;
+                    const existingBrandIndex = brandsData.findIndex(b => b.brand === brand);
+                    if (existingBrandIndex !== -1) {
+                      brandsData[existingBrandIndex].qty += qty;
+                    } else {
+                      brandsData.push({ brand, qty });
+                    }
+                  }
+                }
+
+                const categoryNameS = product.category_name;
+                if (Array.isArray(categoryNameS)) {
+                  for (let i = 0; i < categoryNameS.length; i += 2) {
+                    const name = categoryNameS[i];
+                    const qty = 1;
+                    const existingCategoryIndex = categoriesData.findIndex(c => c.name === name);
+                    if (existingCategoryIndex !== -1) {
+                      categoriesData[existingCategoryIndex].qty += qty;
+                    } else {
+                      categoriesData.push({ name, qty });
+                    }
+                  }
+                }
+              }
+            });
+
+            return Promise.all(dataBrandCategory);
+          }
+        });
+
+        await Promise.all(dataBrandCategoryPromises);
+        setBrands(brandsData);
+        setCategories(categoriesData);
+        setLoading(false);
+
+      } catch (loadError) {
+        // console.error("Error loading promo items:", loadError)
+        setLoading(false);
+      }
+    }
+
+    if (slug) {
+      loadPromo()
+    }
+  },[slug, brand, category, priceFrom, priceTo, currentPage]);
+
+
+  function capitalizeFirstLetter(string) {
+    string = string.replace(/_/g, ' ');
+    return string.replace(/(^\w|\s\w)/g, function(match) {
+        return match.toUpperCase();
+    });
+  }
+
+  const handleDeleteFilter = async (source, value) => {
+    let params = {
+      q: router.query.q,
+      orderBy: '',
+      brand: brandValues.join(','),
+      category: categoryValues.join(','),
+      priceFrom: priceFrom || '',
+      priceTo: priceTo || '',
+    };
+
+    let brands = brandValues;
+    let catagories = categoryValues;
+    switch (source) {
+      case 'brands':
+        brands = brandValues.filter((item) => item !== value);
+        params.brand = brands.join(',');
+        await setBrandValues(brands);
+        break;
+      case 'category':
+        catagories = categoryValues.filter((item) => item !== value);
+        params.category = catagories.join(',');
+        await setCategoryValues(catagories);
+        break;
+      case 'price':
+        params.priceFrom = '';
+      params.priceTo = '';    
+      break;
+      case 'delete':
+        params = {
+          q: router.query.q,
+          orderBy: '',
+          brand: '',
+          category: '',
+          priceFrom: '',
+          priceTo: '',
+        };
+        break;
+    }
+
+    handleSubmitFilter(params);
+  };
+  const handleSubmitFilter = (params) => {
+    params = _.pickBy(params, _.identity);
+    params = toQuery(params);
+    router.push(`${slug}?${params}`);
+  };
+ 
+  const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
+
+  const toQuery = (obj) => {
+    const str = Object.keys(obj)
+      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
+      .join('&')
+    return str
+  }
+ 
+  const whatPromo = capitalizeFirstLetter(slug)
+  const queryWithoutSlug = _.omit(router.query, ['slug'])
+  const queryString = toQuery(queryWithoutSlug)
+  
+  return (
+    <BasicLayout>
+      <Seo
+        title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`} 
+        description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
+      />
+      <Promocrumb brandName={whatPromo} />
+      <MobileView>
+        <div className='p-4 pt-0'>
+          <h1 className='mb-2 font-semibold text-h-sm'>Promo {whatPromo}</h1>
+      
+            <FilterChoicesComponent
+                  brandValues={brandValues}
+                  categoryValues={categoryValues}
+                  priceFrom={priceFrom}
+                  priceTo={priceTo}
+                  handleDeleteFilter={handleDeleteFilter}
+                />
+            {promoItems.length >= 1 && (
+            <div className='flex items-center gap-x-2 mb-5 justify-between'>
+              <div>
+                <button
+                  className='btn-light py-2 px-5 h-[40px]'
+                  onClick={popup.activate}
+                >
+                  Filter
+                </button>
+              </div>
+            </div>
+          )}
+          
+          {loading ? (
+                <div className='container flex justify-center my-4'>
+                  <LogoSpinner width={48} height={48} />
+                </div>
+              ) : promoData && promoItems.length >= 1 ? (
+                <>
+                <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
+                  {visiblePromotions?.map((promotion) => (
+                    <div key={promotion.id} className="min-w-36 max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                      <ProductPromoCard promotion={promotion}/>
+                    </div>
+                  ))}
+                </div>
+              </>
+              ) : (
+                <div className="text-center my-8">
+                  <p>Belum ada promo pada kategori ini</p>
+                </div>
+              )}  
+
+              <Pagination
+                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
+                  currentPage={currentPage}
+                  url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
+                  className='mt-6 mb-2'
+                />
+              <ProductFilter
+                active={popup.active}
+                close={popup.deactivate}
+                brands={brands || []}
+                categories={categories || []}
+                prefixUrl={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                defaultBrand={null}
+              />
+        </div>
+
+      </MobileView>
+      <DesktopView>
+        <div className='container mx-auto flex mb-3 flex-col'>
+          <div className='w-full pl-6'>
+            <h1 className='text-2xl mb-2 font-semibold'>Promo {whatPromo}</h1>
+              <div className=' w-full h-full flex flex-row items-center '>
+                
+                    <div className='detail-filter w-1/2 flex justify-start items-center  mt-4'>
+
+                  <FilterChoicesComponent
+                    brandValues={brandValues}
+                    categoryValues={categoryValues}
+                    priceFrom={priceFrom}
+                    priceTo={priceTo}
+                    handleDeleteFilter={handleDeleteFilter}
+                  />
+                    </div>
+                    <div className='Filter w-1/2 flex flex-col'>
+
+                    <ProductFilterDesktop
+                          brands={brands || []}
+                          categories={categories || []}  
+                          prefixUrl={'/shop/promo'}
+                          // defaultBrand={null}
+                        />
+                    </div>
+                </div>
+              {loading ? (
+                <div className='container flex justify-center my-4'>
+                  <LogoSpinner width={48} height={48} />
+                </div>
+              ) : promoData && promoItems.length >= 1 ? (
+                <>
+                <div className='grid grid-cols-1 gap-x-6  sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3'>
+                  {products?.map((promotion) => (
+                    <div key={promotion.id} className="min-w-[400px] max-w-[400px]  mb-[20px] sm:min-w-[350px] md:min-w-[380px] lg:min-w-[400px] xl:min-w-[400px] ">
+                      <ProductPromoCard promotion={promotion}/>
+                    </div>
+                  ))}
+                </div>
+              </>
+              ) : (
+                <div className="text-center my-8">
+                  <p>Belum ada promo pada kategori ini</p>
+                </div>
+              )}          
+              <div className='flex justify-between items-center mt-6 mb-2'>
+                <div className='pt-2 pb-6 flex items-center gap-x-3'>
+                  <NextImage
+                    src='/images/logo-question.png'
+                    alt='Logo Question Indoteknik'
+                    width={60}
+                    height={60}
+                  />
+                  <div className='text-gray_r-12/90'>
+                    <span>
+                      Barang yang anda cari tidak ada?{' '}
+                      <a
+                        href={
+                          router.query?.q
+                            ? whatsappUrl('productSearch', {
+                                name: router.query.q,
+                              })
+                            : whatsappUrl()
+                        }
+                        className='text-danger-500'
+                      >
+                        Hubungi Kami
+                      </a>
+                    </span>
+                  </div>
+                </div>
+
+                
+                
+                <Pagination
+                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
+                  currentPage={currentPage}
+                  url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
+                  className='mt-6 mb-2'
+                />
+              </div>
+
+          </div>
+        </div>
+      </DesktopView>
+    </BasicLayout>
+  )
+  }
+  
+const FilterChoicesComponent = ({
+  brandValues,
+  categoryValues,
+  priceFrom,
+  priceTo,
+  handleDeleteFilter,
+  }) => (
+  <div className='flex items-center mb-4'>
+    <HStack spacing={2} className='flex-wrap'>
+      {brandValues?.map((value, index) => (
+        <Tag
+          size='lg'
+          key={index}
+          borderRadius='lg'
+          variant='outline'
+          colorScheme='gray'
+          >
+          <TagLabel>{value}</TagLabel>
+          <TagCloseButton onClick={() => handleDeleteFilter('brands', value)} />
+        </Tag>
+      ))}
+
+      {categoryValues?.map((value, index) => (
+        <Tag
+          size='lg'
+          key={index}
+          borderRadius='lg'
+          variant='outline'
+          colorScheme='gray'
+          >
+          <TagLabel>{value}</TagLabel>
+          <TagCloseButton
+            onClick={() => handleDeleteFilter('category', value)}
+            />
+        </Tag>
+      ))}
+      {priceFrom && priceTo && (
+        <Tag size='lg' borderRadius='lg' variant='outline' colorScheme='gray'>
+          <TagLabel>
+            {formatCurrency(priceFrom) + '-' + formatCurrency(priceTo)}
+          </TagLabel>
+          <TagCloseButton
+            onClick={() => handleDeleteFilter('price', priceFrom)}
+            />
+        </Tag>
+      )}
+      {brandValues?.length > 0 ||
+      categoryValues?.length > 0 ||
+      priceFrom ||
+      priceTo ? (
+        <span>
+          <button
+            className='btn-transparent py-2 px-5 h-[40px] text-red-700'
+            onClick={() => handleDeleteFilter('delete')}
+            >
+            Hapus Semua
+          </button>
+        </span>
+      ) : (
+        ''
+        )}
+    </HStack>
+  </div>
+);
-- 
cgit v1.2.3


From b30e6a53d660f9ccbc0ded640c2a1dc5df673ff2 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Mon, 2 Sep 2024 16:43:25 +0700
Subject: <iman> update fetch data

---
 src/pages/shop/promo/[slug].jsx | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

(limited to 'src/pages/shop/promo/[slug].jsx')

diff --git a/src/pages/shop/promo/[slug].jsx b/src/pages/shop/promo/[slug].jsx
index 544286f9..ce73ebd1 100644
--- a/src/pages/shop/promo/[slug].jsx
+++ b/src/pages/shop/promo/[slug].jsx
@@ -24,7 +24,7 @@ import whatsappUrl from '../../../core/utils/whatsappUrl.js';
 import { cons, toQuery } from 'lodash-contrib';
 import _ from 'lodash';
 import useActive from '../../../core/hooks/useActive.js';
-import useProductSearch from '../../../lib/product/hooks/useProductSearch.js';
+import useProductSearch from '../../../lib/promo/hooks/usePromotionSearch.js';
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout.jsx'))
 
@@ -45,7 +45,7 @@ export default function PromoDetail() {
   const popup = useActive();
   const prefixUrl = `/shop/promo/${slug}`
   const [queryFinal, setQueryFinal] = useState({});
-  const [limit, setLimit] = useState<number>(30);
+  const [limit, setLimit] = useState(30);
   const [q, setQ] = useState('*');
   const [finalQuery, setFinalQuery] = useState({fq: `type_value_s:${slug}`});
   const [products, setProducts] = useState(null);
@@ -365,7 +365,7 @@ export default function PromoDetail() {
               ) : promoData && promoItems.length >= 1 ? (
                 <>
                 <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
-                  {visiblePromotions?.map((promotion) => (
+                  {products?.map((promotion) => (
                     <div key={promotion.id} className="min-w-36 max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
-- 
cgit v1.2.3


From dab7f8a1ebd135d9335f1a53346c91d32a2be9f9 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 3 Sep 2024 08:46:46 +0700
Subject: <iman> update tempt

---
 src/pages/shop/promo/[slug].jsx | 25 +++++++++++++++++++------
 1 file changed, 19 insertions(+), 6 deletions(-)

(limited to 'src/pages/shop/promo/[slug].jsx')

diff --git a/src/pages/shop/promo/[slug].jsx b/src/pages/shop/promo/[slug].jsx
index ce73ebd1..71ce8344 100644
--- a/src/pages/shop/promo/[slug].jsx
+++ b/src/pages/shop/promo/[slug].jsx
@@ -37,7 +37,7 @@ export default function PromoDetail() {
   const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
   const [loading, setLoading] = useState(true);
   const { isMobile, isDesktop } = useDevice()
-  const [brands, setBrands] = useState([]);
+  // const [brands, setBrands] = useState([]);
   const [categories, setCategories] = useState([]);
   const [brandValues, setBrandValues] = useState([]);
   const [categoryValues, setCategoryValues] = useState([]);
@@ -75,7 +75,20 @@ export default function PromoDetail() {
 
   console.log("products",products)
 
-
+  const brands = [];
+  for (
+    let i = 0;
+    i < productSearch.data?.facetCounts?.facetFields?.manufactureNameS.length;
+    i += 2
+  ) {
+    const brand =
+      productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i];
+    const qty =
+      productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i + 1];
+    if (qty > 0) {
+      brands.push({ brand, qty });
+    }
+  }
 
 
 
@@ -403,13 +416,13 @@ export default function PromoDetail() {
                 
                     <div className='detail-filter w-1/2 flex justify-start items-center  mt-4'>
 
-                  <FilterChoicesComponent
+                  {/* <FilterChoicesComponent
                     brandValues={brandValues}
                     categoryValues={categoryValues}
                     priceFrom={priceFrom}
                     priceTo={priceTo}
                     handleDeleteFilter={handleDeleteFilter}
-                  />
+                  /> */}
                     </div>
                     <div className='Filter w-1/2 flex flex-col'>
 
@@ -470,8 +483,8 @@ export default function PromoDetail() {
                 
                 
                 <Pagination
-                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
-                  currentPage={currentPage}
+                  pageCount={pageCount}
+                  currentPage={parseInt(page)}
                   url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
                   className='mt-6 mb-2'
                 />
-- 
cgit v1.2.3


From 105ffc8cfa4d8efd51bb7654bfdd279df2a64779 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 3 Sep 2024 12:19:44 +0700
Subject: <iman> update tempt

---
 src/pages/shop/promo/[slug].jsx | 27 ++++++++++++++++++++++-----
 1 file changed, 22 insertions(+), 5 deletions(-)

(limited to 'src/pages/shop/promo/[slug].jsx')

diff --git a/src/pages/shop/promo/[slug].jsx b/src/pages/shop/promo/[slug].jsx
index 71ce8344..169ea0b5 100644
--- a/src/pages/shop/promo/[slug].jsx
+++ b/src/pages/shop/promo/[slug].jsx
@@ -38,14 +38,14 @@ export default function PromoDetail() {
   const [loading, setLoading] = useState(true);
   const { isMobile, isDesktop } = useDevice()
   // const [brands, setBrands] = useState([]);
-  const [categories, setCategories] = useState([]);
+  // const [categories, setCategories] = useState([]);
   const [brandValues, setBrandValues] = useState([]);
   const [categoryValues, setCategoryValues] = useState([]);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy);
   const popup = useActive();
   const prefixUrl = `/shop/promo/${slug}`
   const [queryFinal, setQueryFinal] = useState({});
-  const [limit, setLimit] = useState(30);
+  const [limit, setLimit] = useState(22);
   const [q, setQ] = useState('*');
   const [finalQuery, setFinalQuery] = useState({fq: `type_value_s:${slug}`});
   const [products, setProducts] = useState(null);
@@ -78,18 +78,35 @@ export default function PromoDetail() {
   const brands = [];
   for (
     let i = 0;
-    i < productSearch.data?.facetCounts?.facetFields?.manufactureNameS.length;
+    i < productSearch.data?.facet_counts?.facet_fields?.manufacture_name_s.length;
     i += 2
   ) {
     const brand =
-      productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i];
+      productSearch.data?.facet_counts?.facet_fields?.manufacture_name_s[i];
     const qty =
-      productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i + 1];
+      productSearch.data?.facet_counts?.facet_fields?.manufacture_name_s[i + 1];
     if (qty > 0) {
       brands.push({ brand, qty });
     }
   }
 
+  console.log("brands",brands)
+
+  const categories = [];
+  for (
+    let i = 0;
+    i < productSearch.data?.facet_counts?.facet_fields?.category_name.length;
+    i += 2
+  ) {
+    const name = productSearch.data?.facet_counts?.facet_fields?.category_name[i];
+    const qty =
+      productSearch.data?.facet_counts?.facet_fields?.category_name[i + 1];
+    if (qty > 0) {
+      categories.push({ name, qty });
+    }
+  }
+  
+
 
 
 
-- 
cgit v1.2.3


From ad168bf46919b46f708625b7d2fdc56606ec9af6 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 3 Sep 2024 14:01:02 +0700
Subject: <iman> update all promo fix

---
 src/pages/shop/promo/[slug].jsx | 272 +++++++---------------------------------
 1 file changed, 43 insertions(+), 229 deletions(-)

(limited to 'src/pages/shop/promo/[slug].jsx')

diff --git a/src/pages/shop/promo/[slug].jsx b/src/pages/shop/promo/[slug].jsx
index 169ea0b5..cfb2c841 100644
--- a/src/pages/shop/promo/[slug].jsx
+++ b/src/pages/shop/promo/[slug].jsx
@@ -4,12 +4,9 @@ import { useEffect, useState } from 'react'
 import { useRouter } from 'next/router'
 import Seo from '../../../core/components/Seo.jsx'
 import Promocrumb from '../../../lib/promo/components/Promocrumb.jsx'
-import { fetchPromoItemsSolr, fetchVariantSolr } from '../../../api/promoApi.js'
 import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
 import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card.tsx'
-import { IPromotion } from '../../../../src-migrate/types/promotion.ts'
 import React from 'react'
-import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
 import DesktopView from '../../../core/components/views/DesktopView.jsx';
 import MobileView from '../../../core/components/views/MobileView.jsx';
 import 'swiper/swiper-bundle.css';
@@ -19,9 +16,7 @@ import ProductFilter from '../../../lib/product/components/ProductFilter.jsx';
 import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
 import { formatCurrency } from '../../../core/utils/formatValue.js';
 import Pagination from '../../../core/components/elements/Pagination/Pagination.js';
-import SideBanner from '../../../../src-migrate/modules/side-banner/index.tsx';
 import whatsappUrl from '../../../core/utils/whatsappUrl.js';
-import { cons, toQuery } from 'lodash-contrib';
 import _ from 'lodash';
 import useActive from '../../../core/hooks/useActive.js';
 import useProductSearch from '../../../lib/promo/hooks/usePromotionSearch.js';
@@ -30,39 +25,54 @@ const BasicLayout = dynamic(() => import('../../../core/components/layouts/Basic
 
 export default function PromoDetail() {
   const router = useRouter()
-  const { slug = '', brand ='', category='', priceFrom = '', priceTo = '', page = '1' } = router.query
-  const [promoItems, setPromoItems] = useState([])
-  const [promoData, setPromoData] = useState(null)
+  const { slug = '', brand ='', category='', page = '1' } = router.query
   const [currentPage, setCurrentPage] = useState(parseInt(10) || 1);
-  const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
-  const [loading, setLoading] = useState(true);
-  const { isMobile, isDesktop } = useDevice()
-  // const [brands, setBrands] = useState([]);
-  // const [categories, setCategories] = useState([]);
-  const [brandValues, setBrandValues] = useState([]);
-  const [categoryValues, setCategoryValues] = useState([]);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy);
   const popup = useActive();
   const prefixUrl = `/shop/promo/${slug}`
   const [queryFinal, setQueryFinal] = useState({});
-  const [limit, setLimit] = useState(22);
+  const [limit, setLimit] = useState(30);
   const [q, setQ] = useState('*');
-  const [finalQuery, setFinalQuery] = useState({fq: `type_value_s:${slug}`});
+  const [finalQuery, setFinalQuery] = useState({});
   const [products, setProducts] = useState(null);
+  const [brandValues, setBrand] = useState(
+    !router.pathname.includes('brands')
+      ? router.query.brand
+        ? router.query.brand.split(',')
+        : []
+      : []
+  );
+  
+  const [categoryValues, setCategory] = useState(
+    router.query?.category?.split(',') || router.query?.category?.split(',')
+  );
+  
+  const [priceFrom, setPriceFrom] = useState(router.query?.priceFrom || null);
+  const [priceTo, setPriceTo] = useState(router.query?.priceTo || null);
+
+
   useEffect(() => {
-    setQueryFinal({ ...finalQuery, q, limit, orderBy });
+    const newQuery = {
+      fq: `type_value_s:${slug}`,
+      page : router.query.page? router.query.page : 1,
+      brand : router.query.brand? router.query.brand : '',
+      category : router.query.category? router.query.category : '',
+      priceFrom : router.query.priceFrom? router.query.priceFrom : '',
+      priceTo : router.query.priceTo? router.query.priceTo : '',
+      limit : router.query.limit? router.query.limit : '',
+      orderBy : router.query.orderBy? router.query.orderBy : ''
+    };
+    setFinalQuery(newQuery);
 }, [router.query, prefixUrl, slug, brand, category, priceFrom, priceTo, currentPage]);
   useEffect(() => {
       setQueryFinal({ ...finalQuery, q, limit, orderBy });
-  }, [router.query, prefixUrl, slug, brand, category, priceFrom, priceTo, currentPage]);
+  }, [router.query, prefixUrl, slug, brand, category, priceFrom, priceTo, currentPage, finalQuery]);
 
   const { productSearch } = useProductSearch({
     query: queryFinal,
     operation: 'OR',
   });
 
-  console.log("productSearch",productSearch)
-  console.log("queryFinal",queryFinal)
 
   const pageCount = Math.ceil(productSearch.data?.response.numFound / limit);
   const productStart = productSearch.data?.responseHeader.params.start;
@@ -73,8 +83,6 @@ export default function PromoDetail() {
     setProducts(productSearch.data?.response?.products);
   }, [productSearch]);
 
-  console.log("products",products)
-
   const brands = [];
   for (
     let i = 0;
@@ -90,8 +98,6 @@ export default function PromoDetail() {
     }
   }
 
-  console.log("brands",brands)
-
   const categories = [];
   for (
     let i = 0;
@@ -105,190 +111,6 @@ export default function PromoDetail() {
       categories.push({ name, qty });
     }
   }
-  
-
-
-
-
-
-  useEffect(() => {
-    if (router.query.brand) {
-      let brandsArray= [];
-      if (Array.isArray(router.query.brand)) {
-        brandsArray = router.query.brand;
-      } else if (typeof router.query.brand === 'string') {
-        brandsArray = router.query.brand.split(',').map((brand) => brand.trim());
-      }
-      setBrandValues(brandsArray);
-    } else {
-      setBrandValues([]);
-    }
-
-    if (router.query.category) {
-      let categoriesArray= [];
-
-      if (Array.isArray(router.query.category)) {
-        categoriesArray = router.query.category;
-      } else if (typeof router.query.category === 'string') {
-        categoriesArray = router.query.category.split(',').map((category) => category.trim());
-      }
-      setCategoryValues(categoriesArray);
-    } else {
-      setCategoryValues([]);
-    }
-  }, [router.query.brand, router.query.category]);
-
-  useEffect(() => {
-    const loadPromo = async () => {
-      setLoading(true);
-      const brandsData = [];
-      const categoriesData= [];
-      
-      const pageNumber = Array.isArray(page) ? parseInt(page[0], 10) : parseInt(page, 10);
-      setCurrentPage(pageNumber)
-      
-      try {
-        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`,0,10);
-        setPromoItems(items);
-        
-        if (items.length === 0) {
-          setPromoData([])
-          setLoading(false);
-          return;
-          }
-          
-          const brandArray = Array.isArray(brand) ? brand : brand.split(',');
-          const categoryArray = Array.isArray(category) ? category : category.split(',');
-          
-          const promoDataPromises = items.map(async (item) => {
-            
-            try { 
-              let brandQuery = '';
-              if (brand) {
-                brandQuery = brandArray.map(b => `manufacture_name_s:${b}`).join(' OR ');
-                brandQuery = `(${brandQuery})`;
-              }
-  
-              let categoryQuery = '';
-              if (category) {
-                categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
-                categoryQuery = `(${categoryQuery})`;
-              }
-  
-              let priceQuery = '';
-              if (priceFrom && priceTo) {
-                priceQuery = `price_f:[${priceFrom} TO ${priceTo}]`;
-              } else if (priceFrom) {
-                priceQuery = `price_f:[${priceFrom} TO *]`;
-              } else if (priceTo) {
-                priceQuery = `price_f:[* TO ${priceTo}]`;
-              }
-  
-              let combinedQuery = '';
-              let combinedQueryPrice = `${priceQuery}`;
-              if (brand && category && priceFrom || priceTo) {
-                combinedQuery = `${brandQuery} AND ${categoryQuery} `;
-              } else if (brand && category) {
-                combinedQuery = `${brandQuery} AND ${categoryQuery}`;
-              } else if (brand && priceFrom || priceTo) {
-                combinedQuery = `${brandQuery}`;
-              } else if (category && priceFrom || priceTo) {
-                combinedQuery = `${categoryQuery}`;
-              } else if (brand) {
-                combinedQuery = brandQuery;
-              } else if (category) {
-                combinedQuery = categoryQuery;
-              }
-  
-              if (combinedQuery && priceFrom || priceTo) {
-                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
-                const product = response.response.docs[0];
-                const product_id = product.id;
-                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`,0,100);  
-                return response2;
-              }else if(combinedQuery){
-                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
-                const product = response.response.docs[0];
-                const product_id = product.id;
-                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `,0,100); 
-                return response2;
-              } else {
-                const response = await fetchPromoItemsSolr(`id:${item.id}`,0,100);
-                return response;
-              }
-            } catch (fetchError) {
-              return [];
-            }
-          });
-
-        const promoDataArray = await Promise.all(promoDataPromises);
-        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
-        setPromoData(mergedPromoData);
-
-        const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
-          if (promoData) {
-            const dataBrandCategory = promoData.map(async (item) => {
-              let response;
-              if(category){
-                const categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
-                response = await fetchVariantSolr(`id:${item.products[0].product_id} AND (${categoryQuery})`);
-              }else{
-                response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
-              }
-              
-
-              if (response.response?.docs?.length > 0) {
-                const product = response.response.docs[0];
-                const manufactureNameS = product.manufacture_name;
-                if (Array.isArray(manufactureNameS)) {
-                  for (let i = 0; i < manufactureNameS.length; i += 2) {
-                    const brand = manufactureNameS[i];
-                    const qty = 1;
-                    const existingBrandIndex = brandsData.findIndex(b => b.brand === brand);
-                    if (existingBrandIndex !== -1) {
-                      brandsData[existingBrandIndex].qty += qty;
-                    } else {
-                      brandsData.push({ brand, qty });
-                    }
-                  }
-                }
-
-                const categoryNameS = product.category_name;
-                if (Array.isArray(categoryNameS)) {
-                  for (let i = 0; i < categoryNameS.length; i += 2) {
-                    const name = categoryNameS[i];
-                    const qty = 1;
-                    const existingCategoryIndex = categoriesData.findIndex(c => c.name === name);
-                    if (existingCategoryIndex !== -1) {
-                      categoriesData[existingCategoryIndex].qty += qty;
-                    } else {
-                      categoriesData.push({ name, qty });
-                    }
-                  }
-                }
-              }
-            });
-
-            return Promise.all(dataBrandCategory);
-          }
-        });
-
-        await Promise.all(dataBrandCategoryPromises);
-        setBrands(brandsData);
-        setCategories(categoriesData);
-        setLoading(false);
-
-      } catch (loadError) {
-        // console.error("Error loading promo items:", loadError)
-        setLoading(false);
-      }
-    }
-
-    if (slug) {
-      loadPromo()
-    }
-  },[slug, brand, category, priceFrom, priceTo, currentPage]);
-
 
   function capitalizeFirstLetter(string) {
     string = string.replace(/_/g, ' ');
@@ -302,7 +124,7 @@ export default function PromoDetail() {
       q: router.query.q,
       orderBy: '',
       brand: brandValues.join(','),
-      category: categoryValues.join(','),
+      category: categoryValues?.join(','),
       priceFrom: priceFrom || '',
       priceTo: priceTo || '',
     };
@@ -344,7 +166,6 @@ export default function PromoDetail() {
     router.push(`${slug}?${params}`);
   };
  
-  const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
 
   const toQuery = (obj) => {
     const str = Object.keys(obj)
@@ -355,7 +176,6 @@ export default function PromoDetail() {
  
   const whatPromo = capitalizeFirstLetter(slug)
   const queryWithoutSlug = _.omit(router.query, ['slug'])
-  const queryString = toQuery(queryWithoutSlug)
   
   return (
     <BasicLayout>
@@ -375,7 +195,7 @@ export default function PromoDetail() {
                   priceTo={priceTo}
                   handleDeleteFilter={handleDeleteFilter}
                 />
-            {promoItems.length >= 1 && (
+            {products?.length >= 1 && (
             <div className='flex items-center gap-x-2 mb-5 justify-between'>
               <div>
                 <button
@@ -387,12 +207,10 @@ export default function PromoDetail() {
               </div>
             </div>
           )}
-          
-          {loading ? (
-                <div className='container flex justify-center my-4'>
+          {productSearch.isLoading && <div className='container flex justify-center my-4'>
                   <LogoSpinner width={48} height={48} />
-                </div>
-              ) : promoData && promoItems.length >= 1 ? (
+                </div>}
+          {products && (
                 <>
                 <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
                   {products?.map((promotion) => (
@@ -402,15 +220,11 @@ export default function PromoDetail() {
                   ))}
                 </div>
               </>
-              ) : (
-                <div className="text-center my-8">
-                  <p>Belum ada promo pada kategori ini</p>
-                </div>
-              )}  
+              ) }
 
               <Pagination
-                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
-                  currentPage={currentPage}
+                  pageCount={pageCount}
+                  currentPage={parseInt(page)}
                   url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
                   className='mt-6 mb-2'
                 />
@@ -433,13 +247,13 @@ export default function PromoDetail() {
                 
                     <div className='detail-filter w-1/2 flex justify-start items-center  mt-4'>
 
-                  {/* <FilterChoicesComponent
+                  <FilterChoicesComponent
                     brandValues={brandValues}
                     categoryValues={categoryValues}
                     priceFrom={priceFrom}
                     priceTo={priceTo}
                     handleDeleteFilter={handleDeleteFilter}
-                  /> */}
+                  />
                     </div>
                     <div className='Filter w-1/2 flex flex-col'>
 
@@ -451,11 +265,11 @@ export default function PromoDetail() {
                         />
                     </div>
                 </div>
-              {loading ? (
+              {productSearch.isLoading ? (
                 <div className='container flex justify-center my-4'>
                   <LogoSpinner width={48} height={48} />
                 </div>
-              ) : promoData && promoItems.length >= 1 ? (
+              ) : products && products.length >= 1 ? (
                 <>
                 <div className='grid grid-cols-1 gap-x-6  sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3'>
                   {products?.map((promotion) => (
-- 
cgit v1.2.3

